package com.whty.cms.filewps.util;

import com.alibaba.fastjson.JSON;
import com.whty.cms.filewps.common.constants.Consts;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class WPSUtil {


    private static String contentType = "application/json";
    private static String wpsAppId = MemcacheUtil.getDatabaseObj("wpsAppId");//"AK20220122OGEYAJ";
    private static String wpsAppKey = MemcacheUtil.getDatabaseObj("wpsAppKey");//"bd356bf16db8f0c9a6e319ff0b152bab";
    private static String wpsPrefix = MemcacheUtil.getDatabaseObj("wpsPrefix");//"https://fc-wpslinux.huijiaoyun.com/open";

    //V6版本ak,sk
    private static String wpsV6AppId = MemcacheUtil.getDatabaseObj("wpsV6AppId");
    private static String wpsV6AppKey = MemcacheUtil.getDatabaseObj("wpsV6AppKey");

    private static String getWpsToken = "/auth/v1/app/inscope/token";
    private static String getWpsPreviewUrl = "/preview/v2/url";

    /**
     * 时间格式转码 Wed, 23 Jan 2013 06:43:08 GMT
     *
     * @param date
     * @return
     */
    public static String dateTrans(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // 设置时区为GMT
        String dateStr = sdf.format(date);
        return dateStr;
    }


    /**
     * 标准sha1算法
     *
     * @param str
     * @return
     */
    public static String getSha1(String str) {
        if (null == str || 0 == str.length()) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * MD5值算法
     *
     * @return
     */
    public static String getMd5(String str) {
        String fileMd5 = DigestUtils.md5Hex(str);
        return fileMd5;
    }

    /**
     * WPS签名算法
     *
     * @return
     */
    public static String getWPSAuth(String url) {
        String sha = getSha1(wpsAppKey + url);
        //String s = "WPS-3:AK20220122OGEYAJ:"+sha;
        String s = "WPS-3:" + wpsAppId + ":" + sha;
        return s;
    }

    /**
     * WPS签名算法
     *
     * @return
     */
    public static String getWpsToken() throws Exception {
        String url = getWpsToken + "?app_id=" + wpsAppId + "&scope=file_preview";
        String md5 = getMd5("");
        String date = dateTrans(new Date());
        String auth = getWPSAuth(md5 + url + contentType + date);

        HttpGet httpGet = new HttpGet(wpsPrefix + url);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response;
        String responseContent = "";
        httpGet.addHeader("Content-Type", "application/json");
        httpGet.addHeader("Date", date);
        httpGet.addHeader("Content-Md5", md5);
        httpGet.addHeader("X-Auth", auth);
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        responseContent = EntityUtils.toString(entity, "UTF-8");
        if (StringUtils.isNotBlank(responseContent)) {
            JSONObject jsonObj = JSONObject.fromObject(responseContent);
            if (jsonObj.optInt("result") == 0) {
                JSONObject tokenObj = jsonObj.optJSONObject("token");
                String token = tokenObj.optString("app_token");
                return token;
            }
        }
        return null;
    }


    public static String getpreviewUrl(String fid) throws Exception {
        String url = getWpsPreviewUrl + "?app_token=" + getWpsToken() + "&file_id=" + fid + "&scene_id=2112241840328635";
        String md5 = getMd5("");
        String date = dateTrans(new Date());
        String auth = getWPSAuth(md5 + url + contentType + date);

        HttpGet httpGet = new HttpGet(wpsPrefix + url);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response;
        String responseContent = "";
        httpGet.addHeader("Content-Type", "application/json");
        httpGet.addHeader("Date", date);
        httpGet.addHeader("Content-Md5", md5);
        httpGet.addHeader("X-Auth", auth);
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        responseContent = EntityUtils.toString(entity, "UTF-8");
        if (StringUtils.isNotBlank(responseContent)) {
            JSONObject jsonObj = JSONObject.fromObject(responseContent);
            if (jsonObj.optInt("result") == 0) {
                String previewUrl = jsonObj.optString("url");
                return previewUrl;
            }
        }
        return null;
    }


    public static String getpreviewUrlV4(String fid, String fileExt) {
        String type = null;
        if (Consts.wordList.contains(fileExt)) {
            type = "w";
        } else if (Consts.xlsList.contains(fileExt)) {
            type = "s";
        } else if (Consts.pptList.contains(fileExt)) {
            type = "p";
        } else if ("pdf".equals(fileExt)) {
            type = "f";
        }
        String url = "https://fc-wpslinuxv2.huijiaoyun.com/open/api/preview/v1/files/" + fid + "/link?type=" + type;

        //获取uri路径
        String path = "/api/preview/v1/files/" + fid + "/link?type=" + type;

        String date = dateTrans(new Date());
        //open不参与签名，做替换处理
        if (path.startsWith("/open")) {
            path = path.replace("/open", "");
        }
        String sha256body;
        //body为空则为空，否则返回sha256(body)

        sha256body = "";
        //hmac-sha256(secret_key, Ver + HttpMethod + URI + Content-Type + Wps-Date + sha256(HttpBody))
        String signature = null;
        try {
            signature = HMacUtils.HMACSHA256("WPS-4GET" + path + contentType + date + sha256body, wpsV6AppKey);
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpClient client = HttpClients.createDefault();
            CloseableHttpResponse response;
            String responseContent = "";
            httpGet.addHeader("Content-Type", "application/json");
            httpGet.addHeader("Wps-Docs-Date", date);
            httpGet.addHeader("Wps-Docs-Authorization", String.format("WPS-4 %s:%s", wpsV6AppId, signature));
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
            System.out.println("请求预览地址返回结果：" + responseContent);
            if (StringUtils.isNotBlank(responseContent)) {
                JSONObject jsonObj = JSONObject.fromObject(responseContent);
                if (jsonObj.optInt("code") == 200) {
                    JSONObject data = jsonObj.optJSONObject("data");
                    String previewUrl = data.optString("link");
                    return previewUrl;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String preload(String fid) throws Exception {

        String url = "https://fc-wpsonline.huijiaoyun.com/open/api/preview/v2/files/" + fid + "/versions/1/preload";

        //获取uri路径
        String path = "/api/preview/v2/files/" + fid + "/versions/1/preload";

        String date = dateTrans(new Date());
        //open不参与签名，做替换处理
        if (path.startsWith("/open")) {
            path = path.replace("/open", "");
        }
        String sha256body;
        //body为空则为空，否则返回sha256(body)

        JSONObject requestBody = new JSONObject();
        requestBody.put("webhook", "https://filecenter.huijiaoyun.com/filecenter/v4/v1/3rd/file/version/1");
        sha256body = JSON.toJSONString(requestBody);

        //hmac-sha256(secret_key, Ver + HttpMethod + URI + Content-Type + Wps-Date + sha256(HttpBody))
        String signature = null;
        try {
            String signStr = "WPS-4POST" + path + contentType + date + getContentSha256(sha256body);
            System.out.println("签名串：" + signStr);
            signature = HMacUtils.HMACSHA256(signStr, "u4lrIS4ZB8IRz0N9MR2hGfuIAPyFGNOx");
        } catch (Exception e) {
            e.printStackTrace();
        }

        HttpPost request = new HttpPost(url);

        String responseContent = "";
        request.addHeader("Content-Type", "application/json");
        request.addHeader("Wps-Docs-Date", date);
        request.addHeader("Wps-Docs-Authorization", String.format("WPS-4 %s:%s", "XNDQWNASOOCKQGSN", signature));
        request.setEntity(new StringEntity(sha256body, "UTF-8"));
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        responseContent = EntityUtils.toString(entity, "UTF-8");
        System.out.println("请求预览地址返回结果：" + responseContent);
        if (StringUtils.isNotBlank(responseContent)) {
            JSONObject jsonObj = JSONObject.fromObject(responseContent);
            if (jsonObj.optInt("code") == 200) {
                JSONObject data = jsonObj.optJSONObject("data");
                String previewUrl = data.optString("link");
                return previewUrl;
            }
        }
        return null;
    }


    /**
     * 获取请求body MD5
     *
     * @param content 请求body
     * @return
     */
    private static String getContentSha256(String content) {
        if (org.apache.commons.lang.StringUtils.isBlank(content)) {
            return "";
        } else {
            return DigestUtils.sha256Hex(content);
        }
    }


    public static String getEditUrl(String fid,String fileExt) throws Exception {
        String type = null;
        if (Consts.wordList.contains(fileExt)) {
            type = "w";
        } else if (Consts.xlsList.contains(fileExt)) {
            type = "s";
        } else if (Consts.pptList.contains(fileExt)) {
            type = "p";
        } else if ("pdf".equals(fileExt)) {
            type = "f";
        }
        String url = "https://fc-wpsonline.huijiaoyun.com/open/api/edit/v1/files/" + fid + "/link?type=" + type;

        //获取uri路径
        String path = "/api/edit/v1/files/" + fid + "/link?type=" + type;

        String date = dateTrans(new Date());
        //open不参与签名，做替换处理
        if (path.startsWith("/open")) {
            path = path.replace("/open", "");
        }
        String sha256body = "";
        //body为空则为空，否则返回sha256(body)



        //hmac-sha256(secret_key, Ver + HttpMethod + URI + Content-Type + Wps-Date + sha256(HttpBody))
        String signature = null;
        try {
            String signStr = "WPS-4POST" + path + contentType + date + sha256body;
            System.out.println("签名串：" + signStr);
            signature = HMacUtils.HMACSHA256(signStr, "u4lrIS4ZB8IRz0N9MR2hGfuIAPyFGNOx");
        } catch (Exception e) {
            e.printStackTrace();
        }

        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response;
        String responseContent = "";
        httpGet.addHeader("Content-Type", "application/json");
        httpGet.addHeader("Wps-Docs-Date", date);
        httpGet.addHeader("Wps-Docs-Authorization", String.format("WPS-4 %s:%s", "XNDQWNASOOCKQGSN", signature));
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();

        responseContent = EntityUtils.toString(entity, "UTF-8");
        System.out.println("请求预览地址返回结果：" + responseContent);
        if (StringUtils.isNotBlank(responseContent)) {
            JSONObject jsonObj = JSONObject.fromObject(responseContent);
            if (jsonObj.optInt("code") == 200) {
                JSONObject data = jsonObj.optJSONObject("data");
                String previewUrl = data.optString("link");
                return previewUrl;
            }
        }
        return null;
    }


}
